package com.yfj.shiro.realm;

import com.yfj.dao.ShiroDao;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    ShiroDao shiroDao;

    @Override
    public void setName(String name) {
        super.setName("customRealm");
    }


    //此类里的username对应数据库里的id

    //做授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo
    (PrincipalCollection principalCollection) {

        String username= (String) principalCollection.getPrimaryPrincipal();
        Set<String> roles=getRolesByUserName(username);
        Set<String > permissions=getPermissionsByUserName(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    //数据库获取权限
    private Set<String> getPermissionsByUserName(String username) {
        Set<String> sets=shiroDao.getPermissionsByUserName(username);
        return sets;
    }

    //数据库获取角色
    private Set<String> getRolesByUserName(String username) {
        Set<String> sets = shiroDao.getRolesByUserName(username);
        return sets;
    }

    //做认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo
    (AuthenticationToken authenticationToken) throws AuthenticationException {

        //1.通过传过来的主体信息获取用户名
        String username = (String) authenticationToken.getPrincipal();

        //2.通过用户名去数据库获取密码
        String password=getPassWordByUserName(username);
        if(password==null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo
                (username,password,"customRealm");
        //告诉customRealm盐是多少
        //用"megalovania"做盐
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("megalovania"));
        return authenticationInfo;
    }

    //模拟数据库
    private String getPassWordByUserName(String username) {
        String password=shiroDao.getPassWordByUserName(username);
        return password;
    }

}
